package org.example.JVM.ByteCode.Util;

import org.example.JVM.ByteCode.Handler.*;
import org.example.JVM.ByteCode.Type.ClassFile;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @description:
 * @author: farprt
 * @create: 2022-11-13 13:47
 **/
public class ClassFileAnalysiser {

    private final static List<BaseByteCodeHandler> handlers = new ArrayList<>();

    static {
        //添加各项解释器
        handlers.add(new MagicHandler());
        handlers.add(new VersionHandler());
        handlers.add(new ConstantPoolHandler());
        handlers.add(new AccessFlagsHandler());
        handlers.add(new ThisAndSuperClassHandler());
        handlers.add(new InterfacesHandler());
        handlers.add(new FieldHandler());
        handlers.add(new MethodHandler());
        handlers.add(new AttributesHandler());
        //解析器排序，要按顺序调用
        handlers.sort(Comparator.comparingInt(BaseByteCodeHandler::order));
    }

    /**
     * @param codeBuf class文件内容的字节缓存，从class文件中读取而来
     * @return: {@link ClassFile}
     * @Author: farprt
     * @date: 2022/11/13 13:52
     * @description: 将传入的从class文件读取的字节缓存，解析生成一个ClassFile对象
     */
    public static ClassFile analysis(ByteBuffer codeBuf) throws Exception {
        //重置ByteBuffer读指针，从头开始
        codeBuf.position(0);
        ClassFile classFile = new ClassFile();
        //遍历解析器，调用每个解析器的解析方法
        for (BaseByteCodeHandler handler : handlers) {
            handler.read(codeBuf, classFile);
        }
        System.out.println("class文件结构解析完成，解析是否正常（剩余为解析的字节数）："+codeBuf.remaining());
        return classFile;
    }

}